/*
 * Copyright 2016 requery.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.requery.ohos.example.app;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import io.requery.ohos.example.app.model.Person;
import io.requery.ohos.example.app.slice.PeopleActivity;
import io.requery.ohos.example.app.utils.LogUtil;

import io.requery.ohos.sqlcipher.SqlCipherDatabaseSource;
import io.requery.ohos.sqlitex.SqlitexDatabaseSource;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

import io.requery.Persistable;
import io.requery.ohos.example.app.model.Models;
import io.requery.ohos.sqlite.DatabaseSource;
import io.requery.reactivex.ReactiveSupport;
import io.requery.reactivex.ReactiveEntityStore;
import io.requery.sql.Configuration;
import io.requery.sql.EntityDataStore;
import io.requery.sql.TableCreationMode;

import java.sql.SQLException;

/**
 * PeopleApplication
 */
public class PeopleApplication extends Ability {
    private static final String TAG = PeopleApplication.class.getName();
    private ReactiveEntityStore<Persistable> dataStore;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        dataStore = getData();
        createDB();
        super.setMainRoute(PeopleActivity.class.getName());
    }

    private void createDB() {
        dataStore.count(Person.class).get().single()
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) {
                        if (integer == 0) {
                            Observable.fromCallable(new CreatePeople(dataStore))
                                    .flatMap(new Function<Observable<Iterable<Person>>, Observable<?>>() {
                                        @Override
                                        public Observable<?> apply(Observable<Iterable<Person>> obj) {
                                            return obj;
                                        }
                                    }).observeOn(Schedulers.computation())
                                    .subscribe(new Consumer<Object>() {
                                        @Override
                                        public void accept(Object obj) throws SQLException {
                                            LogUtil.info(TAG, "Post Database Creation");
                                        }
                                    });
                        }
                    }
                });
    }

    /**
     * db_Path = /data/user/0/io.requery.ohos.example.app/databases/my_db.db
     *
     * To open Database using SqlCipherDatabaseSource -->
     * SqlCipherDatabaseSource source = new SqlCipherDatabaseSource(this, Models.DEFAULT,db_Path,pswd, 1);
     *
     * or To open Database using SqlitexDatabaseSource -->
     * SqlitexDatabaseSource source = new SqlitexDatabaseSource(this, Models.DEFAULT,DB_Path, 1);
     *
     * @return {@link EntityDataStore} single instance for the application.
     * <p/>
     * Note if you're using Dagger you can make this part of your application level module returning
     * {@code @Provides @Singleton}.
     */
    public ReactiveEntityStore<Persistable> getData() {
        if (dataStore == null) {
            // override onUpgrade to handle migrating to a new version
            //
            DatabaseSource source = new DatabaseSource(this, Models.DEFAULT, 1);
            if (BuildConfig.DEBUG) {
                // use this in development mode to drop and recreate the tables on every upgrade
                source.setTableCreationMode(TableCreationMode.CREATE_NOT_EXISTS);
            }
            Configuration configuration = source.getConfiguration();
            dataStore = ReactiveSupport.toReactiveStore(
                    new EntityDataStore<Persistable>(configuration));
        }
        return dataStore;
    }
}
